<template>
  <div class="bigbox">
    <!-- 导航查询栏 -->
     <div class="topbox">
       <el-form ref="form" label-position="left" label-width="80px">
           <el-row :gutter="20">
               <el-col :span="5">
                 <el-form-item label="用电企业">
                  <el-select v-model="bizOrgName" style="width: 100%;" placeholder="请选择" size="small" ref="shou"  >
                    <el-option class="option" :label="bizOrgName" value="value" >
                          <el-tree
                          :props="props"
                          :load="loadNode"
                          lazy
                          @node-click="handleNodeClick"
                          ref="tree"
                          >
                        </el-tree>
                      </el-option>
                  </el-select>
                 </el-form-item>
               </el-col>
               <el-col :span="19" style="text-align: right;">
                <el-form-item label="">
                  <el-button @click="submit" type="primary" size="small">查 询</el-button>
                </el-form-item>
               </el-col>
           </el-row>
       </el-form>
     </div>
     <!-- 表格盒子主体 -->
     <div class="bodybox">
      <!-- 新增刷新功能模块 -->
      <div style="display: flex;justify-content: space-between;">
        <div>巡视计划</div>
      <div>
        <el-button type="primary" size="small"  @click="xinzen"><i class="el-icon-upload2"  >新增</i></el-button>
              <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                <span @click="shuaxin"><i class="el-icon-refresh-right" style=" cursor: pointer;"></i></span>
              </el-tooltip>
              <el-dropdown trigger="click" @command="command">
              <span class="el-dropdown-link">
                <el-tooltip class="item" effect="dark" content="密度" placement="top">
                <span><i class="el-icon-d-caret" style=" cursor: pointer;"></i></span>
              </el-tooltip>
              </span>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item command="默认">默认</el-dropdown-item>
                <el-dropdown-item command="中等">中等</el-dropdown-item>
                <el-dropdown-item command="紧凑">紧凑</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
      </div>
      </div>
      <!-- 表格区域模块 -->
      <div class="table">
        <template>
          <el-table
          :size="iissize"
          border
     :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
            v-loading="loading"
            height="calc(100% - 1px)"
          :data="tableData"
          style="width: 100%">
          <template slot="empty">
            <el-empty  description="暂无数据"></el-empty>
          </template>
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="120">
          </el-table-column>
          <el-table-column
            prop="orgName"
            label="用电客户">
          </el-table-column>
          <el-table-column
          prop="businessTypeName"
          label="业务类型"
          align="center">
            
          </el-table-column>
          <el-table-column
            prop="cycle"
            label="巡视周期">
          </el-table-column>
          <el-table-column
            prop="startDate"
            label="开始巡视日期"
            align="center">
          </el-table-column>
          <el-table-column
            prop="content"
            label="巡视内容概述">
            <template #default="{row}">
                  <el-popover
                    placement="bottom"
                    title=""
                    width="200"
                    trigger="click">
                      <div class="lines">巡视内容</div>
                      <el-input
                      style="margin-top: 10px;"
                        type="textarea"
                        :rows="4"
                        placeholder=""
                        v-model="row.content">
                      </el-input>
                    <el-button type="text" slot="reference" class="yichu">{{ row.content }}</el-button>
                  </el-popover>
                </template>
          </el-table-column>
          <el-table-column
            prop="xsfzrName"
            label="巡视人"
            align="center">
          </el-table-column>
          <el-table-column
            prop="xscyName"
            label="巡视成员"
            align="center">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template #default="{row}">
              <el-button type="text" @click="liulan(row)">浏览</el-button>
              <el-button type="text" @click="bianji(row)">编辑</el-button>
              <el-button type="text" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        </template>
      </div>
      <!-- 底部分页 -->
      <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj._pageNo"
                :page-size="10"
                @current-change="getlist"
                :total="+totalCount">
              </el-pagination>
        </div>
        <!-- 新增/编辑弹窗 -->
        <div>
          <el-dialog
            title="巡视周期"
            @close="handercolose"
            :visible.sync="dialogVisible"
            width="45%">
            <div class="dialogbox">
              <el-form :model="form" label-position="left" label-width="100px">
                <el-form-item label="业务类型">
                  <el-radio-group v-model="form.businessType">
                    <el-radio v-for="(item,index) in yewulist" :key="index" :label="item.value">{{item.text}}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="用电企业">
                  <el-select v-model="form.orgNo" filterable  placeholder="请选择" size="small"   style="width: 100%;">
                    <el-option
                    class="options"
                      v-for="item in qiyelist"
                      :key="item.value"
                      :label="item.bizOrgName"
                      :value="item.bizOrgNo">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="周期">
                  <el-input v-model="form.cycle" size="small" style="width: 100%;" placeholder="请输入周期单位为(天)">
                    <span slot="suffix" style="margin-right: 5px;">天</span>
                  </el-input>
                </el-form-item>
                <el-form-item label="开始日期" >
                  <el-input
                  size="small" style="width: 100%;"
                    suffix-icon="el-icon-date"
                    v-model="form.startDate">
                  </el-input>
                </el-form-item>
                <el-form-item label="巡视人员">
                  <!-- <el-input
                  size="small" style="width: 100%;"
                    suffix-icon="el-icon-search"
                    v-model="form.xsfzrName">
                  </el-input> -->
                  <el-select v-model="form.xsfzrName"  size="small" style="width: 100%;" ref="renyuan">
                  <el-option class="option" :label="form.xsfzrName" value="value" >
                        <el-tree
                        :props="propss"
                        :load="loadNodess"
                        lazy
                        @node-click="handleNode"
                        ref="tree">
                        </el-tree>
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="巡视成员">
                  <el-select v-model="formdata.treeData" multiple size="small" @remove-tag="removetag" style="width: 100%;">
                    <el-option value="treeDataValue" label="label" style="height: auto">
                      <el-tree
                        ref="tree"
                        :props="propss"
                        :highlight-current="true"
                        @node-click="handleNodeClicks"
                        :load="loadNodes"
                        lazy>
                        <template slot-scope="{ node, data }">
                          <span :style="{cursor: data.disabled ? 'no-drop' : 'pointer', fontSize: '14px'}">{{ node.label }}</span>
                        </template>
                      </el-tree>
                    </el-option>
                </el-select>
                
                </el-form-item>
                <el-form-item label="巡视内容概括">
                  <el-input
                    type="textarea"
                    :rows="3"
                    style="width: 100%;"
                    placeholder="请输入内容"
                    v-model="form.content">
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer" v-if="isshow">
              <el-button @click="quxiao" size="small">取 消</el-button>
              <el-button type="primary" @click="surecun" size="small">确 定</el-button>
            </span>
          </el-dialog>
        </div>
     </div>
  </div>
</template>

<script>
import {getgengjiedianapi,getzhuzhijigouapi,getuserlistapis} from '@/api/subscribe'
import { getuserlistapi } from '@/api/analysis'
import { getyewuleiapi } from '@/api/guidelines'
import { gettreelist, gettreexiaji } from '../../api/userscreen'
import {getzhouqiapi,postzhouqiapi,delzunshiapi,getyonghuxialaapi,getloginuserapi} from '@/api/cycle'
import  TopTitle from '@/components/TopTitle/index.vue'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTitle
},
  data() {
    return {
      isshow:true,
      form:{orgNo:'',startDate:'',xsfzrId:'',xsfzrName:'',xscyId:'',xscyName:'',businessType:''},
      loading:false,
      iissize: 'medium',
      bizOrgName:'',
      qiyelist: [],
      tableData: [],
      totalCount:'',
      pageobj: {
        _pageNo: 0,
        _pageSize:10
      },
      dialogVisible: false,
      orgNo: '',
      props: {
        label: 'bizOrgName',
      },
      value: '',
      dialogno: '',
      formdata: {
        treeData: [],
        treeidlist:[]
      },
      propss: {
        label: 'orgName',
        disabled:'disabled'
      },
      yewulist:[],
      testList:[]
    };
  },

  async mounted() {
    const re = await getloginuserapi()
    if (re.data.entity.orgType!=='04') {
      const res = await gettreelist()
    this.bizOrgName = res.data.list[0].bizOrgName
    this.value = res.data.list[0].bizOrgNo
    } else {
      const res = await getyonghuxialaapi()
      this.bizOrgName = res.data.list[0].bizOrgName
    this.value = res.data.list[0].bizOrgNo
    }


    const ress = await getuserlistapi()
    this.qiyelist = ress.data.list
    this.dialogno=ress.data.list[0].bizOrgNo

    const resss = await getyewuleiapi({ dictType: 'XSGL_ZYZDSLX' })
        this.yewulist = resss.data.list
    this.getlist()

  },

  methods: {
    // 封装获取表格数据
    async getlist() {
      this.loading=true
      const {data:{totalCount,list}} = await getzhouqiapi({ orgNo: this.value,  _pageNo: this.pageobj._pageNo - 1, _pageSize: this.pageobj._pageSize, })
      this.tableData = list
      this.totalCount=totalCount
      this.loading=false
    },
    // 确认保存/修改
    async surecun() {
      this.form.xscyId = this.formdata.treeidlist.join(',')
      this.form.xscyName=this.formdata.treeData.join(',')
      const orgName = this.qiyelist.filter(ele => ele.bizOrgNo == this.form.orgNo)[0].bizOrgName
      // console.log(this.form.xscyId,this.form.xscyName,orgName);
      await postzhouqiapi({...this.form,orgName})
      this.$message.success('操作成功')
      this.dialogVisible = false
      // this.form.cycle = ''
      // this.form.xsfzrName = ''
      // this.form.xscyName = ''
      // this.form.content = ''
      this.form={}
      this.formdata.treeData = []
      this.formdata.treeidlist = []
      this.getlist()
    },
    // 刷新列表
    shuaxin() {
      this.getlist()
      this.$message.success('列表刷新成功')
    },
    // 取消/弹框关闭
    quxiao() {
      this.dialogVisible = false
      // this.form.cycle = ''
      // this.form.xsfzrName = ''
      // this.form.xscyName = ''
      // this.form.content = ''
      this.form = {}
      this.form.orgNo=''
      this.formdata.treeData = []
      this.formdata.treeidlist=[]
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
       //  获取当前时间错
       gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate()<10?'0'+date.getDate():date.getDate()
      var hour = date.getHours(); // 时
      var minutes = date.getMinutes(); // 分
      var seconds = date.getSeconds() 
      this.form.startDate = year + '-' + month + '-' + day+' ' + hour + ':' + minutes+':'+seconds
    },
    // 新增
    async xinzen() {
      this.form = { orgNo: '', startDate: '', xsfzrId: '', xsfzrName: '', xscyId: '', xscyName: '', businessType: '' }
      this.$set(this.form,'businessType',this.yewulist[0].value)
      this.gettime()
      this.isshow = true
      
      this.form.orgNo = this.dialogno
      this.dialogVisible = true
    },
    // 查询
    submit() {
      this.getlist()
    },
    //编辑
    bianji(row) {
      console.log(row);
      this.isshow=true
      this.form = { ...row }
      this.$set(this.form,'businessType',row.businessType)
      this.formdata.treeData=row.xscyName.split(',')
      this.dialogVisible=true
    },
    // 删除功能
    del(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delzunshiapi({id:row.id})
        this.$message.success('删除成功')
        this.getlist()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 浏览
    liulan(row) {
      this.isshow=false
      this.form = { ...row }
      this.formdata.treeData=row.xscyName.split(',')
      this.dialogVisible = true
    },
    handercolose() {
      this.form = {}
      this.form.orgNo=''
      this.formdata.treeidlist=[]
      this.formdata.treeData=[]
    },
        // 树组件懒加载
    async loadNode(node, resolve) {
      const re = await getloginuserapi()
      if (re.data.entity.orgType!=='04') {
        const res = await gettreelist()
      if (node.level === 0) { // 初始的级数（最顶层）
        return resolve(res.data.list) // 最顶层数据渲染为region
      }
      const ress = await gettreexiaji({ orgNo: node.data.bizOrgNo })
      if (node.level === 1) {
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        return resolve([])
      } 
      } else {
        if (node.level === 0) {
          const res = await getyonghuxialaapi()
        return resolve(res.data.list)
        } else {
          return resolve([])
        }
      }
    },
      // 点击树节点
      handleNodeClick(val) {
        this.value = val.bizOrgNo
      this.bizOrgName=val.bizOrgName
      this.$refs.shou.blur()
    },
       // 树组件懒加载
    async loadNodes(node, resolve) {
      const res = await getgengjiedianapi()
      if (node.level === 0) { // 初始的级数（最顶层）
        const array = [res.data.entity]
        array.forEach(ele => {
          ele.disabled = true
        })
        return resolve(array) // 最顶层数据渲染为region
      }
      const ress = await getzhuzhijigouapi({ parentOrgNo: res.data.entity.orgNo })
      if (node.level === 1) {
        // node.disabled = true;
        ress.data.list.forEach(ele => {
          ele.disabled = true
        })
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const resss=await getuserlistapis({deptNo:node.data.orgNo})
        const newData = resss.data.list.map(obj => {
          return Object.keys(obj).reduce((acc, key) => {
            acc[key === 'userName' ? 'orgName' : key] = obj[key];
            return acc;
          }, {});
        });
        return resolve(newData)
      } else {
        return resolve([])
      }
    },
    handleNodeClicks(data, node, nodeData) {
      if(this.formdata.treeData.some(ele => ele == data.orgName)) return
      this.formdata.treeData.push(data.orgName)
      this.formdata.treeidlist.push(data.userNo)
      this.testList.push({ name: data.orgName, id: data.userNo })
    },
    removetag(val) {
      this.testList=this.testList.filter(ele => ele.name !== val)
      this.formdata.treeidlist = this.testList.map(item => item.id)
    },
    async loadNodess(node, resolve) {
      const res = await getgengjiedianapi()
      if (node.level === 0) { // 初始的级数（最顶层）
        const array = [res.data.entity]
        array.forEach(ele => {
          ele.disabled = true
        })
        return resolve(array) // 最顶层数据渲染为region
      }
      const ress = await getzhuzhijigouapi({ parentOrgNo: res.data.entity.orgNo })
      if (node.level === 1) {
        // node.disabled = true;
        ress.data.list.forEach(ele => {
          ele.disabled = true
        })
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const resss=await getuserlistapis({deptNo:node.data.orgNo})
        const newData = resss.data.list.map(obj => {
          return Object.keys(obj).reduce((acc, key) => {
            acc[key === 'userName' ? 'orgName' : key] = obj[key];
            return acc;
          }, {});
        });
        return resolve(newData)
      } else {
        return resolve([])
      }
    },
    handleNode(val) {
      // this.form.xsfzrName = val.orgName
      this.$set(this.form,'xsfzrName',val.orgName)
      this.form.xsfzrId = val.userNo
      this.$refs.renyuan.blur()
    }
  },
  watch:{
   async dialogVisible (val){
      if(val){
        // 获取类型
        // const resss = await getyewuleiapi({ dictType: 'XSGL_ZYZDSLX' })
        // this.yewulist = resss.data.list
        // this.$set(this.form,'businessType',this.yewulist[0].value)
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.options{
  padding-left: 10px;
  height: auto;
}
.option{
  height: auto;
}
.bigbox{
  height: 100%;
  padding: 10px;
  .topbox{
    padding: 20px;
    height: 80px;
    background-color: #fff;
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    position: relative;
        .item{
          margin-left: 10px;
        }
        .table{
          height: 90%;
          margin-top: 10px;
          .yichu{
          width: 140px;
          white-space: nowrap;
          text-align: left;
          overflow: hidden;  // 超出的文本隐藏
          text-overflow: ellipsis; // 溢出用省略号显示
        }
        }
        .fenye{
        position: absolute;
        bottom: 10px;
        right: 20px;
      }
      .dialogbox{
      //  border: 1px solid #ccc;
      border-top: 1px solid #ccc;
       padding: 20px;
      //  border-radius: 3px;
      }
      .button{
        width: 60px;
        height: 30px;
      }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .el-dialog__body{
  padding: 0 20px;
}
::v-deep .el-radio{
  margin-left:5px;
}
</style>